<?php

    // +----------------------------------------------------------------------
    // | 文件模型
    // +----------------------------------------------------------------------
    // | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
    // +----------------------------------------------------------------------
    // | Author: 微尘 <yicmf@qq.com>
    // +----------------------------------------------------------------------

    namespace app\model\file;

    use think\Config;
	use think\facade\Event;
	use think\File;
    use think\facade\Env;
    use app\model\ucenter\User;

    class Attachment extends Common
    {

    	public static $driver_lists = ['local' => '本地', 'qiniu' => '七牛'];

        public function getInfo($id, $callback = null, $args = null)
        {
            /* 获取文件信息 */
            $attachment = $this->find($id);
            if ( !$attachment ) {
                $this->error = '不存在该文件！';

                return false;
            } else {
                return $attachment;
            }
        }

        /**
         * 处理显示url
         * @param $value
         * @param $data
         * @return string
         * @author  : 微尘 <yicmf@qq.com>
         * @datetime: 2019/3/15 9:30
         */
        public function getUrlAttr($value, $data)
        {

//            if ( 'qiniu' == $data['driver'] && 'qiniu' == self::$config['driver'] ) {
//                $domian = self::$config['qiniu_domain'];
//            } else {
			$domain = self::$request->domain();
//            }
            return $domain . $data['url'];
        }


        /**
         * 下载指定文件.
         * @param number $root 文件存储根目录
         * @param int    $id   文件ID
         * @param string $args 回调函数参数
         * @return bool false-下载失败，否则输出下载文件
         */
        public function download($root, $id, $callback = null, $args = null)
        {
            /* 获取下载文件信息 */
            $attachment = $this->find($id);
            if ( !$attachment ) {
                $this->error = '不存在该文件！';

                return false;
            }

            /* 下载文件 */
            switch ( $attachment['location'] ) {
                case 0: //下载本地文件
                    $attachment['rootpath'] = $root;

                    return $this->downLocalFile($attachment, $callback, $args);
                case 1: //下载FTP文件
                    $attachment['rootpath'] = $root;

                    return $this->downFtpFile($attachment, $callback, $args);
                    break;
                default:
                    $this->error = '不支持的文件存储类型！';

                    return false;

            }
        }


        /**
         * 下载本地文件.
         * @param array    $attachment 文件信息数组
         * @param callable $callback   下载回调函数，一般用于增加下载次数
         * @param string   $args       回调函数参数
         * @return bool 下载失败返回false
         */
        private function downLocalFile($attachment, $callback = null, $args = null)
        {
            if ( is_file($attachment['rootpath'] . $attachment['save_path'] . $attachment['save_name']) ) {
                /* 调用回调函数新增下载数 */
                is_callable($callback) && call_user_func($callback, $args);

                /* 执行下载 */ //TODO: 大文件断点续传
                header('Content-Description: File Transfer');
                header('Content-type: ' . $attachment['type']);
                header('Content-Length:' . $attachment['size']);
                if ( preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) ) { //for IE
                    header('Content-Disposition: attachment; filename="' . rawurlencode($attachment['name']) . '"');
                } else {
                    header('Content-Disposition: attachment; filename="' . $attachment['name'] . '"');
                }
                readfile($attachment['rootpath'] . $attachment['save_path'] . $attachment['save_name']);
                exit;
            } else {
                $this->error = '文件已被删除！';

                return false;
            }
        }

        /**
         * 下载ftp文件.
         * @param array    $attachment 文件信息数组
         * @param callable $callback   下载回调函数，一般用于增加下载次数
         * @param string   $args       回调函数参数
         * @return bool 下载失败返回false
         */
        private function downFtpFile($attachment, $callback = null, $args = null)
        {
            /* 调用回调函数新增下载数 */
            is_callable($callback) && call_user_func($callback, $args);

            $host = Config::get('DOWNLOAD_HOST.host');
            $root = explode('/', $attachment['rootpath']);
            $attachment['save_path'] = $root[3] . '/' . $attachment['save_path'];

            $data = [$attachment['save_path'], $attachment['save_name'], $attachment['name'], $attachment['mime']];
            $data = json_encode($data);
            $key = think_encrypt($data, Config::get('DATA_AUTH_KEY'), 600);

            header("Location:http://{$host}/onethink.php?key={$key}");
        }

        // 定义关联方法
        public function user()
        {
            return $this->belongsTo(User::class);
        }

        //获取器
        public function getSizeInfoAttr($value, $data)
        {
            return format_bytes($data['size']);
        }

        public function getSizeAttr($value, $data)
        {
            return format_bytes($value);
        }

        // 以下是自动完成
		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeInsert($data)
		{
			$data['status'] = 1;
		}
		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeWrite($data)
		{
			$data['url'] = '';
		}

        public function getOriginalAttr($value, $data)
        {
            return $data['url'];
        }
        /**
         * 优化访问url
         * @param unknown $value
         * @param unknown $data
         */
        protected function setUrlAttr($value, $data)
        {
            if (IS_SAFE_MODE) {
                $url = '/' . str_replace(DIRECTORY_SEPARATOR, '/', str_replace(app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR, '', $data['path']));
            } else {
                $url = '/' . str_replace(DIRECTORY_SEPARATOR, '/', $data['path']);
            }

            // 注册图片修改url钩子
			Event::trigger('upload_picture_set_url',$data);
            return $url;
            //        $data['url'] = '/' . str_replace(DIRECTORY_SEPARATOR, '/', str_replace(app()->getRootPath(), '', $data['path']));
            // 注册图片修改url钩子

            //        return $data['url'];
        }
        protected $type = [
            'info' => 'array',
        ];

    }
